#!/bin/bash
echo "********************************************"
echo "此脚本用于安装容器依赖的Docker服务"
echo "********************************************"

function print(){
	echo -e "$2> $1 $3"
}
function print_error(){
	print "$1" '\e[31m' '\e[0m'
}
function print_success(){
	print "$1" '\e[34m' '\e[0m'
}

#确认是否已经安装docker
de=`docker --version 2>/dev/null`
if [ "$?" -eq "0" ];then
	print_error "docker 已安装! \n$de\n安装脚本退出..."
	exit 1;
fi

#确认操作系统位数
_arch=`arch`
if [ "$_arch" != "x86_64" ];then
	print_error "没有找到arch命令，或者不是64操作系统:$_arch，\n安装脚本退出..."
	exit 1;
fi
print_success "CPU架构符合安装要求！"
#确认操作系统内核是否大于3.10
ks=`uname -r`
if [[ "$ks" < "3.10" ]];then
        print_error "系统内核版本小于3.10, kv:$ks \n安装脚本退出..."
        exit 1;
fi
print_success "操作系统内核版本符合安装要求！"
#确信iptables是否大于1.4
iv=`iptables -V|awk '{print $2}'`
if [[ "$iv" < "v1.4" ]];then
        print_error "iptables本小于1.4, iv:$iv \n安装脚本退出..."
        exit 1;
fi

print_success "iptables版本符合安装要求！"
#exit 0;
print "安装docker服务..."

c_dir=$(pwd)
print "当前目录：$c_dir"
tar -zxvf pkgs/${_arch}_docker-*.tgz
if [ "$?" != "0" ];then
	print_error "解压${_arch}_docker-*.tgz失败"
	exit 1
fi
chown -R root:root docker
cp docker/* /usr/bin
rm -rf docker
#echo -e "#Setting docker \nexport PATH=$c_dir"'/docker_bin:$PATH' >  /etc/profile.d/docker.sh

#. /etc/profile
print "添加docker service"
echo -e "
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target
 
[Service]
Type=notify
ExecStart=/usr/bin/dockerd
ExecReload=/bin/kill -s HUP "'$MAINPID'"
LimitNOFILE=infinity
LimitNPROC=infinity
TimeoutStartSec=0
Delegate=yes
KillMode=process
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s
 
[Install]
WantedBy=multi-user.target
" > /lib/systemd/system/docker.service

dc_file="$c_dir/pkgs/docker-compose-linux-x86_64"
chmod +x $dc_file
ln -s /usr/bin/docker-compose $dc_file
#echo -e "[Unit]
#Description=Docker Socket for the API
#
#[Socket]
#ListenStream=/var/run/docker.sock
#SocketMode=0660
#SocketUser=root
#SocketGroup=docker

#[Install]
#WantedBy=sockets.target
#" > /usr/lib/systemd/system/docker.socket

chmod 644 /lib/systemd/system/docker.service
#chmod 644 /usr/lib/systemd/system/docker.socket

systemctl daemon-reload
print "启动Docker服务..."
systemctl --no-pager start docker

if [ "$?" != "0" ];then
        print_error "docker服务安装失败！"
        exit 1
else
	print_success "docker服务安装成功！"
fi
